package com.cy.mycomposedemo


import android.os.Bundle
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.compose.foundation.layout.Column
import androidx.compose.material3.Button
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.State
import androidx.compose.runtime.compositionLocalOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember



class MainActivity1 : ComponentActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContent {
            MyUserScreen()
        }
    }
}

data class User(var name: String, var age: Int)
//val localComposition = compositionLocalOf { mutableStateOf(0) }
val LocalActiveUser = compositionLocalOf<State<User?>> { error("No user found!") }

@Composable
private fun MyUserScreen() {
    val user = User("Jens", 31)
    val stateUser = remember { mutableStateOf<User?>(user) }
    Column {
        CompositionLocalProvider(LocalActiveUser provides stateUser) {
            UserInfo()
        }
        //脱离了compositionLocalOf作用域
//    Text("Name: " + LocalActiveUser.current.value?.name)

        Button(onClick = {
            stateUser.value = User("dada", 33)
//            user.name="lalalala"  //不生效，对象未变
        }) {
            Text(text = "change stateUser")
        }
    }
}


@Composable
fun UserInfo() {
    Column {
        Text("Name: " + LocalActiveUser.current.value?.name)
        Text("Age: " + LocalActiveUser.current.value?.age)
    }
}